package com.example.shop_2302.xq

import android.R.attr.bitmap
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.base.mvvm.BaseActivity
import com.example.base.param.OrderDetail
import com.example.base.param.ParamPreOrder
import com.example.shop_2302.R
import com.example.shop_2302.adapter.CommentAdapter
import com.example.shop_2302.databinding.ActivityXqBinding
import com.example.shop_2302.room.AppDbUtils
import com.example.shop_2302.room.Comment
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.youth.banner.loader.ImageLoader
import java.text.SimpleDateFormat


@Route(path = "/app/XqActivity")
class XqActivity : BaseActivity<ActivityXqBinding,XqViewModel>() {
    val list = mutableListOf<String>()//图片集合
    @Autowired
    @JvmField
    var goodsId = 1

    var attrId = ""//属性id //详情数据请求成功后赋值
    var imgurl = ""//图片地址 //详情数据请求成功后赋值
    lateinit var dialog:AlertDialog
    override fun initView() {
        ARouter.getInstance().inject(this)
        //请求商品详情
        viewModel.xq(goodsId,"normal")
        //点击返回按钮
        binding.ivBack.setOnClickListener {
            finish()
        }
        //点击加入购物车
        binding.addCar.setOnClickListener {
            viewModel.addCar(1,attrId,goodsId)
        }
        //点击立即购买

        //点击用户评价，弹出popupwindow
        binding.tvReply.setOnClickListener {
            val popupWindow = PopupWindow()
            val view = LayoutInflater.from(this).inflate(R.layout.item_pop, null)
            val commentAdapter = CommentAdapter()
            val rv = view.findViewById<RecyclerView>(R.id.rv_comment)
            rv.adapter = commentAdapter
            rv.layoutManager = LinearLayoutManager(this)
            //查询数据
            val queryAll = AppDbUtils.getDb().getCommentDao().queryAll(goodsId)
            commentAdapter.data.clear()
            commentAdapter.data.addAll(queryAll)
            commentAdapter.notifyDataSetChanged()
            //发送评论
            view.findViewById<Button>(R.id.send).setOnClickListener {
                //更新数据库
                val msg = view.findViewById<EditText>(R.id.et).text.toString()
                val comment = Comment(0,SPUtils.getInstance().getString("phone"),"",msg,SimpleDateFormat("yyyy-MM-dd HH:mm").format(System.currentTimeMillis()),goodsId)
                AppDbUtils.getDb().getCommentDao().insert(comment)
                //清空输入框
                view.findViewById<EditText>(R.id.et).setText("")
                //页面显示数据
                commentAdapter.data.add(comment)
                commentAdapter.notifyDataSetChanged()
            }
            //找到searchView的控件
            val sv = view.findViewById<SearchView>(R.id.sv)
            sv.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
                override fun onQueryTextSubmit(query: String?): Boolean {
                    if(query!=null){
                        val query1 = AppDbUtils.getDb().getCommentDao().query(query, goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(query1)
                        commentAdapter.notifyDataSetChanged()
                    }else{
                        val query2 = AppDbUtils.getDb().getCommentDao().queryAll(goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(query2)
                        commentAdapter.notifyDataSetChanged()
                    }
                    return false
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    //实时刷新请求
                    if(newText!=null){
                        val query1 = AppDbUtils.getDb().getCommentDao().query(newText, goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(query1)
                        commentAdapter.notifyDataSetChanged()
                    }else{
                        val query2 = AppDbUtils.getDb().getCommentDao().queryAll(goodsId)
                        commentAdapter.data.clear()
                        commentAdapter.data.addAll(query2)
                        commentAdapter.notifyDataSetChanged()
                    }
                    return false
                }
            })

            popupWindow.width = LayoutParams.MATCH_PARENT
            popupWindow.height = 1000
            popupWindow.contentView = view
            popupWindow.isOutsideTouchable = true
            popupWindow.isFocusable = true//获取焦点,不然edit不能输入内容
            popupWindow.showAtLocation(binding.tvReply,Gravity.BOTTOM,0,0)
        }

        //点击分享图标，实现弹出二维码图片，点击确定按钮，实现分享功能
        binding.ivShare.setOnClickListener {

            val view = LayoutInflater.from(this).inflate(R.layout.item_dialog, null)
            //显示图片
            //生成图片
            val encodeBitmap =
                BarcodeEncoder().encodeBitmap(imgurl, BarcodeFormat.QR_CODE, 200, 200)
            //给控件赋值
            view.findViewById<ImageView>(R.id.iv).setImageBitmap(encodeBitmap)
            //点击取消按钮，关闭对话框
            view.findViewById<TextView>(R.id.no).setOnClickListener {
                dialog.dismiss()
            }
            //点击确定分享，关闭对话框，实现分享功能
            view.findViewById<Button>(R.id.yes).setOnClickListener {
                dialog.dismiss()
                //实现分享
                val image: UMImage = UMImage(this, encodeBitmap) //bitmap文件  一定替换为真正的bitmap图片
                ShareAction(this).withText("hello").withMedia(image)
                    .setDisplayList(SHARE_MEDIA.QQ)
                    .setCallback(object :UMShareListener{
                        override fun onStart(p0: SHARE_MEDIA?) {
                            ToastUtils.showLong("开始分享")
                        }

                        override fun onResult(p0: SHARE_MEDIA?) {

                        }

                        override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                            ToastUtils.showLong(p1?.message)
                        }

                        override fun onCancel(p0: SHARE_MEDIA?) {

                        }
                    })
                    .open()


            }
            dialog= AlertDialog.Builder(this)
                .setTitle("提示")
                .setView(view)
                .create()
            dialog.show()

        }


        //点击购物车 ，可以跳转到购物车界面 //跳转到 首页，告知首页我要显示第3个fragment
        binding.tvGocar.setOnClickListener {
            ARouter.getInstance().build("/app/ShopActivity").withInt("position",2).navigation()
        }
        binding.ivGocar.setOnClickListener {
            ARouter.getInstance().build("/app/ShopActivity").withInt("position",2).navigation()
        }
        //点击立即购买
        binding.buyNow.setOnClickListener {
            val paramPreOrder = ParamPreOrder()
            paramPreOrder.preOrderType = "buyNow"//预下单类型
            //订单明细 可能有多个商品使用list集合
            val list = mutableListOf<OrderDetail>()
            var orderDetail = OrderDetail()
            //购买商品   商品id  商品属性id  商品数量
            orderDetail.productId = goodsId
            orderDetail.attrValueId = attrId.toInt()//加入购物车是添加过，但是是字符串类型的
            orderDetail.productNum = 1

            //将商品添加到集合中
            list.add(orderDetail)
            //将集合添加到参数中
            paramPreOrder.orderDetails = list

            viewModel.preOrder(paramPreOrder)
        }
    }

    override fun initData() {
        viewModel.xqSuccess.observe(this){
            if(it.code==200){
                binding.info = it.data.productInfo//给布局中的详情info赋值
                //给默认选中的属性赋值
                binding.tvSelected.text = "已选择：${it.data.productValue.keys.toList()[0]}"//获取map中key值中的第一个、
                attrId = it.data.productValue.values.toList()[0].id.toString()//默认选中的属性的id   为map的value的第一个的id
                imgurl = it.data.productInfo.image//图片地址

                list.add(it.data.productInfo.image)
                list.add(it.data.productInfo.image)
                binding.banner.setImages(list)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null&&imageView!=null) {
                                Glide.with(context).load(path).into(imageView)
                            }
                        }

                    })
                    .start()
                //有部分项目存在详情中播放视频  videoView(vp,第一个fragment显示videoview，第二个fragment放banner)
               /* binding.vv.setVideoPath("")//视频可正常播放
                binding.vv.setMediaController(MediaController(this))*/

            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                //添加成功，展示动画
                //定义一个图片
                val imageView = ImageView(this)
                val layoutParams = LayoutParams(200, 200)
                imageView.layoutParams = layoutParams
                Glide.with(this).load(imgurl).into(imageView)
                //显示到布局上
                binding.main.addView(imageView)
                //对 图片添加动画
                //屏幕宽高
                val width = windowManager.defaultDisplay.width.toFloat()
                val height = windowManager.defaultDisplay.height.toFloat()
                //设计动画
                val translationX =
                    ObjectAnimator.ofFloat(imageView, "translationX", 0f, width, width * 2 / 3-200)
                val translationY = ObjectAnimator.ofFloat(imageView, "translationY", 0f, height)

                val animatorSet = AnimatorSet()
                animatorSet.duration = 2000
                animatorSet.play(translationX).with(translationY)
                animatorSet.start()
                animatorSet.addListener(object:Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {

                    }

                    override fun onAnimationEnd(animation: Animator) {
                        binding.main.removeView(imageView)
                    }

                    override fun onAnimationCancel(animation: Animator) {

                    }

                    override fun onAnimationRepeat(animation: Animator) {

                    }
                })


            }
        }
        viewModel.preSuccess.observe(this){
            if(it.code==200){
                //ToastUtils.showLong(it.data.preOrderNo)
                ARouter.getInstance().build("/app/CreateOrderActivity").withString("preOrderNo",it.data.preOrderNo).navigation()
            }else{
                ToastUtils.showLong(it.message)
            }

        }
    }

    override fun getViewModel(): Class<XqViewModel>  = XqViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_xq

}